from rest_framework.views import APIView
from rest_framework.response import Response
from rest_framework import status
from rest_framework.decorators import api_view
from django.db.models import Sum, F, Q
from apps.UMM.models import Attendance, User
from apps.OMM.models import Order, Host_order
import datetime
import pandas as pd
from django.http import HttpResponse
import calendar
from decimal import Decimal
import random
import json

# 添加一个测试视图函数，用于测试API路径是否可以访问
@api_view(['GET'])
def test_salary_api(request):
    """
    测试薪资API访问
    """
    return Response({
        'code': 200,
        'message': '薪资API测试成功',
        'data': {
            'timestamp': datetime.datetime.now().isoformat(),
            'path': request.path
        }
    })

# 添加一个生成测试数据的API端点
@api_view(['GET'])
def generate_test_salary_data(request):
    """
    生成测试薪资数据，用于前端开发测试
    """
    month = request.query_params.get('month', datetime.datetime.now().strftime('%Y-%m'))
    page = int(request.query_params.get('page', 1))
    limit = int(request.query_params.get('limit', 10))
    nickname = request.query_params.get('nickname', '')
    
    # 创建模拟员工
    employees = ['客服1', '客服2', '客服3', '客服4', '客服5']
    
    # 如果指定了员工，只返回该员工的数据
    if nickname:
        employees = [nickname] if nickname in employees else employees
    
    # 生成测试数据
    test_data = []
    for emp in employees:
        hourly_wage = float(random.randint(500, 1500))
        commission = float(random.randint(200, 2000))
        total_salary = hourly_wage + commission
        
        test_data.append({
            'month': month,
            'nickname': emp,
            'hourly_wage': hourly_wage,
            'commission': commission,
            'total_salary': total_salary,
            'work_hours': random.randint(40, 200),
            'order_count': random.randint(1, 20)
        })
    
    # 排序 - 按总薪资从高到低
    test_data.sort(key=lambda x: x['total_salary'], reverse=True)
    
    # 总数据量
    total_count = len(test_data)
    
    # 分页
    start_idx = (page - 1) * limit
    end_idx = min(start_idx + limit, total_count)
    paginated_data = test_data[start_idx:end_idx]
    
    return Response({
        'code': 200,
        'message': '获取测试薪资数据成功',
        'data': {
            'total': total_count,
            'items': paginated_data
        }
    })

# 添加一个生成测试薪资详情的API端点
@api_view(['GET'])
def generate_test_salary_detail(request):
    """
    生成测试薪资详情数据，用于前端开发测试
    """
    month = request.query_params.get('month', datetime.datetime.now().strftime('%Y-%m'))
    nickname = request.query_params.get('nickname', '客服1')
    
    # 生成基础数据
    hourly_wage = float(random.randint(500, 1500))
    commission = float(random.randint(200, 2000))
    total_salary = hourly_wage + commission
    work_hours = random.randint(40, 200)
    order_count = random.randint(1, 20)
    
    # 生成时薪明细
    hourly_wage_details = []
    for i in range(5):
        day = random.randint(1, 28)
        date_str = f"{month}-{day:02d}"
        hours = random.randint(2, 8)
        rate = 30.0
        amount = float(hours * rate)
        
        hourly_wage_details.append({
            'date': date_str,
            'hours': hours,
            'rate': rate,
            'amount': amount,
            'remark': '正常值班'
        })
    
    # 生成提成明细
    commission_details = []
    for i in range(order_count):
        day = random.randint(1, 28)
        date_str = f"{month}-{day:02d}"
        is_double = random.random() > 0.7
        amount = float(random.randint(50, 150))
        
        commission_details.append({
            'order_id': f"ORD-{random.randint(1000, 9999)}",
            'comm_type': '激活提成',
            'is_double': is_double,
            'amount': amount,
            'date': date_str,
            'remark': '产品激活提成'
        })
    
    detail_data = {
        'month': month,
        'nickname': nickname,
        'hourly_wage': hourly_wage,
        'commission': commission,
        'total_salary': total_salary,
        'work_hours': work_hours,
        'order_count': order_count,
        'hourly_wage_details': hourly_wage_details,
        'commission_details': commission_details
    }
    
    return Response({
        'code': 200,
        'message': '获取测试薪资详情成功',
        'data': detail_data
    })

# 添加新的API端点，用于获取客服用户列表
class CustomerServiceUserListAPI(APIView):
    """
    获取客服用户列表（用于薪资筛选）
    """
    def get(self, request):
        # 只查询参与薪资计算的用户，基于is_commission_calc字段而不是角色
        users = User.objects.filter(is_commission_calc=1).order_by('nickname')
        
        # 准备用户列表数据
        user_list = []
        for user in users:
            user_list.append({
                'value': user.nickname,  # 用于表单值
                'label': user.nickname   # 用于显示
            })
        
        return Response({
            'code': 200,
            'message': '获取客服用户列表成功',
            'data': user_list
        })

class SalaryListAPI(APIView):
    """
    获取薪资列表
    """
    def get(self, request):
        # 获取查询参数
        page = int(request.query_params.get('page', 1))
        limit = int(request.query_params.get('limit', 10))
        month = request.query_params.get('month', '')  # 格式：YYYY-MM
        nickname = request.query_params.get('nickname', '')
        
        # 构造查询条件
        if month:
            year, month_num = map(int, month.split('-'))
            start_date = datetime.date(year, month_num, 1)
            _, last_day = calendar.monthrange(year, month_num)
            end_date = datetime.date(year, month_num, last_day)
        else:
            # 默认显示当前月份
            today = datetime.date.today()
            start_date = datetime.date(today.year, today.month, 1)
            _, last_day = calendar.monthrange(today.year, today.month)
            end_date = datetime.date(today.year, today.month, last_day)
            month = f"{today.year}-{today.month:02d}"

        # 查询用户列表 - 根据is_commission_calc字段筛选，参与薪资计算的用户
        if nickname:
            users = User.objects.filter(nickname__icontains=nickname, is_commission_calc=1)
        else:
            users = User.objects.filter(is_commission_calc=1)
            
        # 准备薪资列表
        salary_list = []
        
        # 为每个用户计算薪资
        for user in users:
            # 计算时薪（从考勤表获取）
            attendance_records = Attendance.objects.filter(
                nickname=user,
                duty_date__gte=start_date,
                duty_date__lte=end_date
            )
            hourly_wage = attendance_records.aggregate(Sum('hourly_wage'))['hourly_wage__sum'] or Decimal('0.0')
            work_hours = sum([record.online_duration for record in attendance_records])
            
            # 计算提成（从订单表获取）
            orders = Order.objects.filter(
                nickname=user,
                activation_date__gte=start_date,
                activation_date__lte=end_date,
                order_status=1  # 已激活的订单
            )
            commission = Decimal('0.0')
            for order in orders:
                # 确保commission不为None
                if order.commission is not None:
                    if order.is_double_coms == 1:  # 双倍提成
                        commission += order.commission * 2
                    else:
                        commission += order.commission
            
            # 计算主机出租订单提成
            host_orders = Host_order.objects.filter(
                nickname=user,
                effective_date__gte=start_date,
                effective_date__lte=end_date
            )
            host_commission = Decimal('0.0')
            for host_order in host_orders:
                # 确保commission不为None
                if host_order.commission is not None:
                    host_commission += host_order.commission
            
            # 总提成 = 订单提成 + 主机出租提成
            total_commission = commission + host_commission
            
            # 总薪资 = 时薪 + 总提成
            total_salary = hourly_wage + total_commission
            
            # 总订单数 = 产品订单数 + 主机出租订单数
            total_order_count = orders.count() + host_orders.count()
            
            # 只添加有薪资(时薪或提成)的用户
            if hourly_wage > 0 or total_commission > 0:
                salary_list.append({
                    'month': month,
                    'nickname': user.nickname,
                    'hourly_wage': float(hourly_wage),
                    'commission': float(total_commission),  # 总提成
                    'total_salary': float(total_salary),
                    'work_hours': work_hours,
                    'order_count': total_order_count
                })
        
        # 排序 - 按总薪资从高到低
        salary_list.sort(key=lambda x: x['total_salary'], reverse=True)
        
        # 分页处理
        start_idx = (page - 1) * limit
        end_idx = page * limit
        paginated_list = salary_list[start_idx:end_idx]
        total_count = len(salary_list)
        
        return Response({
            'code': 200,
            'message': '获取薪资数据成功',
            'data': {
                'total': total_count,
                'items': paginated_list
            }
        })

class SalaryDetailAPI(APIView):
    """
    获取薪资详情
    """
    def get(self, request):
        # 获取查询参数
        month = request.query_params.get('month', '')  # 格式：YYYY-MM
        nickname = request.query_params.get('nickname', '')
        
        if not month or not nickname:
            return Response({
                'code': 400,
                'message': '请提供月份和员工昵称'
            }, status=status.HTTP_400_BAD_REQUEST)
        
        # 解析月份
        year, month_num = map(int, month.split('-'))
        start_date = datetime.date(year, month_num, 1)
        _, last_day = calendar.monthrange(year, month_num)
        end_date = datetime.date(year, month_num, last_day)
        
        # 查找用户
        try:
            user = User.objects.get(nickname=nickname)
        except User.DoesNotExist:
            return Response({
                'code': 404,
                'message': '未找到指定用户'
            }, status=status.HTTP_404_NOT_FOUND)
        
        # 计算时薪（从考勤表获取）- 为参与薪资计算的用户计算时薪，基于is_commission_calc字段
        hourly_wage = Decimal('0.0')
        hourly_wage_details = []
        
        if user.is_commission_calc == 1:  # 参与薪资计算的用户
            attendance_records = Attendance.objects.filter(
                nickname=user,
                duty_date__gte=start_date,
                duty_date__lte=end_date
            ).order_by('duty_date')
            
            hourly_wage = attendance_records.aggregate(Sum('hourly_wage'))['hourly_wage__sum'] or Decimal('0.0')
            
            # 准备时薪明细
            for record in attendance_records:
                hourly_wage_details.append({
                    'date': record.duty_date.strftime("%Y-%m-%d"),
                    'hours': record.online_duration,
                    'rate': 5.0,  # 固定时薪率
                    'amount': float(record.hourly_wage),
                    'remark': f"{record.duty_type}"
                })
        
        # 计算提成（从订单表获取）
        orders = Order.objects.filter(
            nickname=user,
            activation_date__gte=start_date,
            activation_date__lte=end_date,
            order_status=1  # 已激活的订单
        ).order_by('activation_date')
        
        commission = Decimal('0.0')
        commission_details = []
        
        for order in orders:
            # 确保commission不为None
            if order.commission is not None:
                order_commission = order.commission
                if order.is_double_coms == 1:  # 双倍提成
                    order_commission *= 2
                
                commission += order_commission
                
                commission_details.append({
                    'order_id': order.order_number,
                    'comm_type': order.product_name.commission_category.commission_category,
                    'is_double': order.is_double_coms == 1,
                    'amount': float(order_commission),
                    'date': order.activation_date.strftime("%Y-%m-%d"),
                    'remark': f"客户: {order.customer_name.customer_name}, 产品: {order.product_name.product_name}"
                })
        
        # 计算主机出租订单提成
        host_orders = Host_order.objects.filter(
            nickname=user,
            effective_date__gte=start_date,
            effective_date__lte=end_date
        ).order_by('effective_date')
        
        host_commission = Decimal('0.0')
        
        for host_order in host_orders:
            # 确保commission不为None
            if host_order.commission is not None:
                host_commission += host_order.commission
                
                # 获取资源租赁分类名称
                from apps.UMM.models import CommissionCategory
                try:
                    comm_category = CommissionCategory.objects.get(commission_category='资源租赁')
                    comm_type = comm_category.commission_category
                except CommissionCategory.DoesNotExist:
                    comm_type = '资源租赁'
                
                commission_details.append({
                    'order_id': host_order.order_number,
                    'comm_type': comm_type,
                    'is_double': False,  # 主机出租订单没有双倍提成
                    'amount': float(host_order.commission),
                    'date': host_order.effective_date.strftime("%Y-%m-%d"),
                    'remark': f"客户: {host_order.customer.customer_name if host_order.customer else '未知'}, 域名: {host_order.domain_name}"
                })
        
        # 总提成 = 订单提成 + 主机出租提成
        total_commission = commission + host_commission
        
        # 总薪资 = 时薪 + 总提成
        total_salary = hourly_wage + total_commission
        
        # 返回详细数据
        detail_data = {
            'month': month,
            'nickname': nickname,
            'hourly_wage': float(hourly_wage),
            'commission': float(total_commission),  # 总提成
            'total_salary': float(total_salary),
            'hourly_wage_details': hourly_wage_details,
            'commission_details': commission_details
        }
        
        return Response({
            'code': 200,
            'message': '获取薪资详情成功',
            'data': detail_data
        })

class SalaryExportAPI(APIView):
    """
    导出薪资数据
    """
    def get(self, request):
        # 获取查询参数
        month = request.query_params.get('month', '')  # 格式：YYYY-MM
        nickname = request.query_params.get('nickname', '')
        
        # 构造查询条件
        if month:
            year, month_num = map(int, month.split('-'))
            start_date = datetime.date(year, month_num, 1)
            _, last_day = calendar.monthrange(year, month_num)
            end_date = datetime.date(year, month_num, last_day)
        else:
            # 默认导出当前月份
            today = datetime.date.today()
            start_date = datetime.date(today.year, today.month, 1)
            _, last_day = calendar.monthrange(today.year, today.month)
            end_date = datetime.date(today.year, today.month, last_day)
            month = f"{today.year}-{today.month:02d}"

        # 查询用户列表 - 基于is_commission_calc字段筛选参与薪资计算的用户
        if nickname:
            users = User.objects.filter(nickname__icontains=nickname, is_commission_calc=1)
        else:
            users = User.objects.filter(is_commission_calc=1)
            
        # 准备导出数据
        export_data = []
        
        # 导入主机出租订单模型
        from apps.OMM.models import Host_order
        
        # 为每个用户计算薪资
        for user in users:
            # 计算时薪（从考勤表获取）- 为参与薪资计算的用户计算时薪
            hourly_wage = Decimal('0.0')
            work_hours = 0
            
            # 所有参与薪资计算的用户都计算时薪
            attendance_records = Attendance.objects.filter(
                nickname=user,
                duty_date__gte=start_date,
                duty_date__lte=end_date
            )
            hourly_wage = attendance_records.aggregate(Sum('hourly_wage'))['hourly_wage__sum'] or Decimal('0.0')
            work_hours = sum([record.online_duration for record in attendance_records])
            
            # 计算提成（从订单表获取）- 所有用户都计算提成，包括管理员
            orders = Order.objects.filter(
                nickname=user,
                activation_date__gte=start_date,
                activation_date__lte=end_date,
                order_status=1  # 已激活的订单
            )
            commission = Decimal('0.0')
            for order in orders:
                # 确保commission不为None
                if order.commission is not None:
                    if order.is_double_coms == 1:  # 双倍提成
                        commission += order.commission * 2
                    else:
                        commission += order.commission
            
            # 计算主机出租订单提成
            host_orders = Host_order.objects.filter(
                nickname=user,
                effective_date__gte=start_date,
                effective_date__lte=end_date
            )
            host_commission = Decimal('0.0')
            for host_order in host_orders:
                # 确保commission不为None
                if host_order.commission is not None:
                    host_commission += host_order.commission
            
            # 总提成 = 订单提成 + 主机出租提成
            total_commission = commission + host_commission
            
            # 总薪资 = 时薪 + 总提成
            total_salary = hourly_wage + total_commission
            
            # 总订单数 = 产品订单数 + 主机出租订单数
            total_order_count = orders.count() + host_orders.count()
            
            # 只添加有薪资数据的用户（时薪或提成）
            if hourly_wage > 0 or total_commission > 0:
                export_data.append({
                    '月份': month,
                    '员工': user.nickname,
                    '时薪(元)': float(hourly_wage),
                    '提成(元)': float(total_commission),
                    '总薪资(元)': float(total_salary),
                    '工作时长(小时)': work_hours,
                    '激活订单数': total_order_count
                })
        
        # 创建DataFrame
        df = pd.DataFrame(export_data)
        
        # 导出为Excel
        response = HttpResponse(content_type='application/vnd.openxmlformats-officedocument.spreadsheetml.sheet')
        response['Content-Disposition'] = f'attachment; filename="薪资数据_{month}.xlsx"'
        
        # 使用pandas导出Excel
        df.to_excel(response, index=False)
        
        return response 